package cn.edu.qzuie.artist.module.td.service.department;

import cn.edu.qzuie.artist.framework.common.exception.ServiceException;
import cn.edu.qzuie.artist.module.td.convert.department.DepartmentConvert;
import cn.edu.qzuie.artist.module.td.dal.dataobject.classinfo.ClassinfoDO;
import cn.edu.qzuie.artist.module.td.dal.dataobject.major.MajorDO;
import cn.edu.qzuie.artist.module.td.dal.mysql.major.MajorMapper;
import cn.edu.qzuie.artist.module.td.service.major.MajorService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.springframework.stereotype.Service;

import org.springframework.validation.annotation.Validated;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;
import cn.edu.qzuie.artist.module.td.controller.admin.department.vo.*;
import cn.edu.qzuie.artist.module.td.dal.dataobject.department.DepartmentDO;
import cn.edu.qzuie.artist.framework.common.pojo.PageResult;
import cn.edu.qzuie.artist.framework.common.pojo.PageParam;
import cn.edu.qzuie.artist.framework.common.util.object.BeanUtils;

import cn.edu.qzuie.artist.module.td.dal.mysql.department.DepartmentMapper;

import javax.annotation.Resource;

import static cn.edu.qzuie.artist.framework.common.exception.util.ServiceExceptionUtil.exception;
import static cn.edu.qzuie.artist.module.td.enums.ErrorCodeConstants.*;

/**
 * 部门 Service 实现类
 *
 * @author 泉信管理员
 */
@Service
@Validated
public class DepartmentServiceImpl implements DepartmentService {

    @Resource
    private DepartmentMapper departmentMapper;
    @Resource
    private MajorMapper majorMapper;

    @Override
    public Long createDepartment(DepartmentSaveReqVO createReqVO) {
        // 插入
        DepartmentDO department = BeanUtils.toBean(createReqVO, DepartmentDO.class);
        if (isDepartExists(createReqVO.getDepartName(), createReqVO.getSchoolId(),null)) {
            throw exception(DEPARTMENT_ALREADY_EXISTS);
        }
        departmentMapper.insert(department);
        // 返回
        return department.getId();
    }


    @Override
    public void updateDepartment(DepartmentSaveReqVO updateReqVO) {
        // 校验存在
        validateDepartmentExists(updateReqVO.getId());
        // 校验插入的班级是否存在
        if (isDepartExists(updateReqVO.getDepartName(), updateReqVO.getSchoolId(), updateReqVO.getId())) {
            throw exception(DEPARTMENT_ALREADY_EXISTS);
        }
        // 更新
        DepartmentDO updateObj = BeanUtils.toBean(updateReqVO, DepartmentDO.class);
        departmentMapper.updateById(updateObj);
    }

    @Override
    public void deleteDepartment(Long id) {
        // 校验此部门下是否存在专业，若不存在，直接删除；存在，则需要把该部门下的所有的专业删除后，才可以删除此部门
        Long majorCount = majorMapper.selectCount(new cn.edu.qzuie.artist.framework.mybatis.core.query.LambdaQueryWrapperX<MajorDO>()
                .eq(MajorDO::getDepartId, id));
        if (majorCount == 0) {
            // 删除
            departmentMapper.deleteById(id);
        } else {
            throw exception(DEPARTMENT_EXISTS_MAJOR);
        }
    }

    private void validateDepartmentExists(Long id) {
        if (departmentMapper.selectById(id) == null) {
            throw exception(DEPARTMENT_NOT_EXISTS);
        }
    }

    /**
     * 校验部门信息是否已经存在
     *
     * @param departName 部门名称
     * @param schoolId       学校ID
     * @param excludeId     排除的ID，用于更新时检查
     * @return 是否存在
     */
    private boolean isDepartExists(String departName, Long schoolId,Long excludeId) {
        // 校验部门是否存在
        DepartmentDO department = departmentMapper.selectOne(new cn.edu.qzuie.artist.framework.mybatis.core.query.LambdaQueryWrapperX<DepartmentDO>()
                .eq(DepartmentDO::getDepartName, departName)
                .eq(DepartmentDO::getDeleted,0)
                .eq(DepartmentDO::getSchoolId,schoolId));
        return department != null && !department.getId().equals(excludeId);
    }

    @Override
    public DepartmentDO getDepartment(Long id) {
        return departmentMapper.selectById(id);
    }

    @Override
    public PageResult<DepartmentDO> getDepartmentPage(DepartmentPageReqVO pageReqVO) {
        return departmentMapper.selectPage(pageReqVO);
    }

    @Override
    public List<DepartmentForSelectVo> getDepartments(Long schoolId) {
      List<DepartmentDO> departments=  departmentMapper.selectList("school_id",schoolId);
      return DepartmentConvert.INSTANCE.convertList(departments);
    }

}